import { WebSocketServer, WebSocket } from 'ws';
import fs from 'fs';
import path from 'path';
import { fileURLToPath } from 'url';

// 获取当前文件的目录路径
const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);

// 创建WebSocket服务器
const wss = new WebSocketServer({ port: 30001 });

// 图片路径
const imageDir = path.join(__dirname, 'images');
const image1Path = path.join(imageDir, '1.png');
const image2Path = path.join(imageDir, '2.png');

// 读取图片并转换为base64
function readImageAsBase64(imagePath: string): string {
    try {
        const imageBuffer = fs.readFileSync(imagePath);
        return imageBuffer.toString('base64');
    } catch (error) {
        console.error(`Error reading image ${imagePath}:`, error);
        return '';
    }
}

// 初始化图片数据
let image1Base64 = readImageAsBase64(image1Path);
let image2Base64 = readImageAsBase64(image2Path);

console.log('WebSocket server is running on port 30001');

wss.on('connection', (ws: WebSocket) => {
    console.log('Client connected');
    let currentImage = 1;

    // 每秒切换一次图片
    const interval = setInterval(() => {
        if (ws.readyState === WebSocket.OPEN) {
            // 切换图片
            const imageData = currentImage === 1 ? image1Base64 : image2Base64;
            ws.send(imageData);
            console.log(`Image ${currentImage} sent`);
            
            // 切换图片索引
            currentImage = currentImage === 1 ? 2 : 1;
        }
    }, 1000);

    ws.on('close', () => {
        console.log('Client disconnected');
        clearInterval(interval);
    });
}); 